package top.ffhome.util.bean;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;

import cn.hutool.core.util.ReflectUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BeanUtil extends cn.hutool.core.bean.BeanUtil {
	/**
	 * 复制指定的字段
	 * @param source
	 * @param target
	 * @param fieldNames
	 */
	public static void copyProperties(Object source, Object target, Collection<String> fieldNames) {
		Field[] fields = ReflectUtil.getFields(target.getClass());
		Object value;
		try {
			for (Field field : fields) {
				if (fieldNames.contains(field.getName())) {
					value = ReflectUtil.getFieldValue(source, field.getName());
					ReflectUtil.setFieldValue(target, field.getName(), value);
				}
			}
		} catch (Exception e) {
			log.warn("copyProperties不可能抛出的异常{}", e.getMessage());
		}
	}

	/**
	 * 将obj中的属性，只保留fieldNames的值，其他都设置为null,fieldNames的size为零时忽略操作
	 * 
	 * @param obj
	 * @param fieldNames
	 */
	public static void constraintProperties(Object obj, Collection<String> fieldNames) {
		if (fieldNames == null || fieldNames.size() == 0) {
			return;
		}
		Field[] fields = ReflectUtil.getFields(obj.getClass());
		for (Field field : fields) {
			if (!Modifier.isStatic(field.getModifiers()) && !fieldNames.contains(field.getName())) {
				try {
					ReflectUtil.setFieldValue(obj, field.getName(), null);
				} catch (Exception e) {
				}
			}
		}
	}

	/**
	 * 去除指定的属性
	 * @param obj
	 * @param fieldNames
	 */
	public static void deleteProperties(Object obj, Collection<String> fieldNames) {
		if (fieldNames == null || fieldNames.size() == 0) {
			return;
		}
		for (String fieldName : fieldNames) {
			try {
				ReflectUtil.setFieldValue(obj, fieldName, null);
			} catch (Exception e) {
			}
		}
	}
}
